package com.oocl.task20170718.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class TaskUtil {
	//yyyy-MM-dd HH:mm:ss
	private static final String DATE_FORMAT = "yyyyMMdd_HHmmss";
	private static final String APP_ROOT_DIR = "file";
	//Singleton pattern better
	private static String appRealRootDir;
	static{
		String appRootDirPre = TaskUtil.class.getResource("/").toString();
		appRootDirPre = appRootDirPre.substring(0, appRootDirPre.indexOf("target/") + "target/".length());
		appRootDirPre = appRootDirPre.substring("file:/".length());
		appRealRootDir = appRootDirPre + APP_ROOT_DIR + "/";
	}
	
	public static String getUuid(){
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
	public static String getTime(){
		SimpleDateFormat sdf=new SimpleDateFormat( TaskUtil.DATE_FORMAT );
		return sdf.format(new Date());
	}
	public static File createFile() {
		String fileName = getTime() + "_" + getUuid() + ".txt";
		File dir = new File(appRealRootDir);
		File file = new File(appRealRootDir + fileName);
		try {
			boolean dirCreateSuc=true;
			if(!dir.exists()){
				dirCreateSuc=dir.mkdirs();				
			}
			if(dirCreateSuc){
				if(!file.exists()){
					file.createNewFile();
				}
			}
		} catch (IOException e) {
			//log;file create fail
		}
		return file;
	}
	public static <T extends Serializable> boolean writeInObjectOutputStream(File file,List<T> list){
		ObjectOutputStream oos=null;
		try {
			oos = new ObjectOutputStream(new FileOutputStream(file));
			oos.writeObject(list);
			if(oos!=null){
				oos.close();
			}
		} catch (FileNotFoundException e) {
			return false;
		} catch (IOException e) {
			return false;
		}finally{
			if(oos!=null){
				try { oos.close(); } catch (IOException e) { /**/ }
			}
		}
		return true;
	}
	public static <T extends Serializable> List<T> readByObjectInputStream(File file,T t){
		List<T> list=new ArrayList<>();
		ObjectInputStream ois=null;
		try {
			ois = new ObjectInputStream(new FileInputStream(file));
			list =  (List<T>) ois.readObject();
			ois.close();
		} catch (ClassNotFoundException | IOException e) { }
		return list;
	}
	
}
